package com.fengwei.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 拒绝访问
 *
 * @author XueLiang
 * @version 1.0
 * @date 2017年3月1日 上午11:07:10
 */
public class RestAccessDeniedHandler implements AccessDeniedHandler {

    private final Logger logger = LoggerFactory.getLogger(AjaxLogoutSuccessHandler.class);

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException, ServletException {
        logger.warn("Authentication Failed: " + accessDeniedException.getMessage());
//        JSONResponse jsonResponse = new JSONResponse();
//        jsonResponse.addError(DefaultException.Error.invalid_parameter.name(), accessDeniedException.getMessage());
        Map map = new HashMap();
        map.put("d-exception", "deny");
        response.addHeader("Content-type", "application/json; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter printWriter = response.getWriter();
        printWriter.write(map.toString());
        printWriter.flush();
        printWriter.close();
    }
}
